<template>
  <div class="container">
    <van-nav-bar title="搜索中心" left-arrow @click-left="$router.back()" />

    <!-------------------------- 搜索框 ----------------------------------->
    <van-search
      v-model="keyWord"
      placeholder="请输入搜索关键词"
      @search="onSearch"
    />

    <!------------------ 根据输入关键词=》联想补全搜索关键词： ---------------->
    <van-cell-group class="suggest-box" v-if="keyWord">
      <!-- span高亮联想关键词 -->
      <van-cell
        icon="search"
        v-for="sug in suggestList"
        :key="sug"
        @click="onSearch(sug.replace(`<span>${keyWord}</span>`, keyWord))"
        ><p v-html="sug"></p
      ></van-cell>
    </van-cell-group>

    <!------------------------ 搜索后的关键词历史记录 --------------------------->
    <div class="history-box" v-else>
      <div class="head">
        <span>历史记录</span>
        <!-- 删除全部 -->
        <van-icon @click="delAllHistory" name="delete"></van-icon>
      </div>
      <van-cell-group v-for="(item, index) in historyList" :key="item">
        <van-cell>
          <a class="word_btn"  @click="onSearch(item)">{{ item }}</a>
          <van-icon
            @click="delHistory(index)"
            class="close_btn"
            slot="right-icon"
            name="cross"
          />
        </van-cell>
      </van-cell-group>
    </div>
  </div>
</template>

<script>
// 造假数据的
// localStorage.setItem('TT_HISTORY', JSON.stringify(['css', 'js', 'HTML']))
import { suggestApi } from '@/api/article.js'
const TT_HISTORY = 'TT_HISTORY'
export default {
  name: 'search-index',
  data () {
    return {
      timer: null,
      suggestList: [],
      // 搜索框输入内容
      keyWord: '',
      historyList: JSON.parse(localStorage.getItem('TT_HISTORY')) || []
    }
  },
  methods: {
    // 搜索框回车时回调函数
    onSearch (val) {
      // console.log(val)
      // 1. 判断非空
      // 2. 存储搜索关键词 => 排重
      // 3. 添加历史记录 并更新数据列表
      // 4. 更新本地历史记录列表
      // 5. 跳转搜索结果页并携带当前搜索关键词
      if (!val) return
      const historySet = new Set(this.historyList)
      historySet.add(val)
      this.historyList = [...historySet]
      localStorage.setItem('TT_HISTORY', JSON.stringify(this.historyList))
      this.$router.push(`/search/result?q=${val}`)
    },
    // 删除一条
    delHistory (index) {
      // 软删除
      this.historyList.splice(index, 1)
      // 硬删除
      localStorage.setItem('TT_HISTORY', JSON.stringify(this.historyList))
    },
    // 删除全部
    delAllHistory () {
      // 软删除
      this.historyList = []
      // 硬删除
      localStorage.setItem('TT_HISTORY', JSON.stringify(this.historyList))
    }
  },
  watch: {
    keyWord () {
      // 如果timer有定时器,清除它, 继续执行下面的代码
      this.keyWord && clearTimeout(this.timer)
      // 延迟600毫秒请求数据
      this.timer = setTimeout(async () => {
        if (!this.keyWord) {
          this.suggestList = []
          return
        }
        try {
          const { data } = await suggestApi(this.keyWord)
          console.log(data)
          if (data.options[0] === null) return
          this.suggestList = data.options.map(
            // function (item) {
            //   item.toLowerCase().replace(this.keyWord, `<span>${this.keyWord}</span>`)
            // }
            (item) =>
              item.toLowerCase().replace(this.keyWord, `<span>${this.keyWord}</span>`)
          )
        } catch (error) {
          console.dir(error)
        }
      }, 600)
    }
  }
}
</script>

<style scoped lang='less'>
// 联想词样式
.suggest-box {
  /deep/ .van-cell {
    padding: 10px 20px;
    color: #999;
    p {
      span {
        color: red;
      }
    }
  }
}
// 历史记录
.history-box {
  padding: 0 20px;
  .head {
    line-height: 36px;
    color: #999;
    text-align: left;
    .van-icon {
      font-size: 16px;
      float: right;
      margin-top: 10px;
    }
  }
  .van-cell {
    padding: 10px 0;
  }
  .word_btn {
    color: #3296fa;
  }
  .close_btn {
    margin-top: 5px;
    color: #999;
  }
}
</style>
